package a.b;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import a.a.R;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

public abstract class SectionAdapter extends BaseAdapter {
	private HashSet<Integer> sectionSet = new HashSet<Integer>();
	private List<String> mList;
	private LayoutInflater mInflater;
	private Context mContext;
	//
	public SectionAdapter(Context context, int sectionLayout, int contentLayout, List<String> data) {
		mContext = context;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		//
		mList = new ArrayList<String>(data);
		String prevLetter = null;
		String firstLetter = null;
		String section = null;
		for (int positon = 0; positon < mList.size(); positon++) {
			// section
			section = mList.get(positon);

			// firstLetter
			if (TextUtils.isEmpty(section)) {
				firstLetter = "etc";
			} else {
				firstLetter = String.valueOf(section.charAt(0));
			}

			//
			if (!firstLetter.equalsIgnoreCase(prevLetter)) {
				// register section
				sectionSet.add(positon);
				mList.add(positon++, firstLetter);
			}
			prevLetter = firstLetter;
		}
	}

	@Override
	public int getCount() {
		return mList.size();
	}

	@Override
	public String getItem(int position) {
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		if (sectionSet.contains(position)) {
			return -1;
		}
		return position;
	}

	private boolean isSection(int position) {
		return getItemId(position) == -1;
	}

	@Override
	public final View getView(int position, View view, ViewGroup parent) {
		boolean isSection = isSection(position);
		View v = view;
		if (v == null) {
			if (isSection) {
				v = mInflater.inflate(R.layout.section, null);
			} else {
				v = mInflater.inflate(R.layout.item, null);
			}
		}

		if (isSection) {
			getSectionView(position, v, parent);
		} else {
			getContentView(position, v, parent);
		}
		return v;
	}
	@Override
	public boolean areAllItemsEnabled() {
		return false;
	}

	@Override
	public int getItemViewType(int position) {
		if (isSection(position)) {
			return 1;
		}
		return super.getItemViewType(position);
	}
	@Override
	public int getViewTypeCount() {
		return super.getViewTypeCount() + 1;
	}

	@Override
	public boolean isEnabled(int position) {
		return !isSection(position);
	}

	protected abstract void getSectionView(int position, View view, ViewGroup parent);
	protected abstract void getContentView(int position, View view, ViewGroup parent);
}
